import React from 'react';
import { inject, observer } from 'mobx-react';
import {Button, Row, Col,Spin} from 'antd';
import {WeaRightMenu,WeaDialog,
        WeaFormItem,WeaUpload,WeaLocaleProvider  } from 'ecCom';
import * as mobx from 'mobx'
import * as FnaButton from '../../public/FnaButton'
import * as FnaMessage from '../../public/FnaMessage'
import {RecognitionStore} from '../../stores/fnaInvoiceIdentify/recognitionStore'
const getLabel = WeaLocaleProvider.getLabel;
import cloneDeep from 'lodash/cloneDeep';

/**
* 识别
*/
@observer
class RecognitionModal extends React.Component {
	constructor(props) {
        super(props);
        this.state = {
            list: [],
            upStatus: ''
        };

        this.recognitionStore = new RecognitionStore();
  }

  componentDidMount(){

  }

  componentWillReceiveProps(nextProps) {
    
  }

  shouldComponentUpdate(nextProps, nextState) {
      return true;
  }

  componentWillUnmount() {
    //组件卸载时一般清理一些状态
    this.clear();

  }


	render(){
        const { componentType,symbol,workflowid,requestid } = this.props;
        const { loading,recognitionModalVisible } = this.recognitionStore;
        let title = getLabel(512309,'发票识别');

        return(
            <div>
                {componentType == 'invoiceRecognition' && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@tmj2cc`} onClick={this.show} type='primary'>{title}</Button>}
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@f2vcgy`}
                    icon='icon-coms-Finance'
                    iconBgcolor='#f14a2d'
                    title={title}
                    visible={recognitionModalVisible}
                    style={{width:550,height:200}}
                    maskClosable={false}
                    onCancel={this.handleCancel}
                    buttons={this.getBottomButton()}
                >
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@polaiu`} datas={this.getRightMenu()} collectParams={{favname:title, favouritetype:5}}>    
                        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@eefe08`} spinning={loading}>
                            {this.getFormData()}
                        </Spin>
                    </WeaRightMenu>
                </WeaDialog>
            </div>
            
        )
	}

  //获取form
  getFormData = (value) => {
        return  <div>
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@7u5jxa`} align={"middle"} className='wea-fna-upload'>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@al5u8t`} span={2}></Col>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@g79gaj`} span={20} style={{marginTop:10}}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@og0kg4`}
                            label={getLabel(387236,'发票图片')}
                            labelCol={{span: `6`}}
                            wrapperCol={{span: `18`}}>
                                {this.getImportFileCompoment()}
                                <div style={{color:'red',marginLeft:'45px', position: 'absolute',top: '0px',right: '50px'}}>
                                    <div>1. {getLabel(513241,'仅限上传jpg,jpeg,png,pdf格式!')}</div>
                                    <div>2. {getLabel(512318,'一次最多添加10张进行识别!')}</div>
                                </div>
                        </WeaFormItem>
                    </Col>
                </Row>
                </div>;
  }

  show = () => {
    const { setRecognitionModal } = this.recognitionStore;;
    setRecognitionModal(true);
  }

  //右下角点击按钮
  getBottomButton = () => {
    const { loading } = this.recognitionStore;
    let buts=[];
    buts.push(FnaButton.getPrimaryButton(this.handleSubmit,loading,getLabel(512319,'识别'),`${this && this.props && this.props.ecId || ''}`));
    buts.push(FnaButton.getPrimaryButton(this.clear,loading,getLabel(519915,'清除'),`${this && this.props && this.props.ecId || ''}`));

    return buts;
  }
  
  //右键菜单
  getRightMenu = () => {
    const { loading } = this.recognitionStore;;
    let btns = [];

    btns.push({
            key:"save",
            icon: <i className="icon-portal-operation-o" />,
            content:getLabel(512319,'识别'),
            disabled:loading,
            onClick:this.handleSubmit
     });
     btns.push({
        key:"clear",
        icon: <i className="icon-coms-Delete" />,
        content:getLabel(519915,'清除'),
        disabled:loading,
        onClick:this.clear
 });
    return btns;
  }
  
  //取消
  handleCancel = () => {
    const { setRecognitionModal } = this.recognitionStore;;
    setRecognitionModal(false);

    this.setState({
        list: [],
        upStatus: ''
    });

  }
  
  //开始识别
  handleSubmit = () => {
    const { excelFileNo,doRecognition } = this.recognitionStore;;
    let { list,upStatus } = this.state;

    if(list.length > 0){
        let formData = {
            fileid:mobx.toJS(excelFileNo),
            operation:'recognition'
        };

        FnaMessage.fnaConfirm(getLabel(512320,'开始识别'),() => {
            this.trainRecognition(excelFileNo);
        });
        
    } else {
       FnaMessage.fnaWarningTip(getLabel(132079,'未选择文件'));
    }
  }

  //上传文件组件
  getImportFileCompoment = () => {
      const { setExcelFileNo,excelFileNo } = this.recognitionStore;;           
      let file = [];
      let {list,upStatus} = this.state;
      let that = this;
      file.push(
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@grhd6c@upLoad_row1`} align={"middle"}>
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@yudp3m@upLoad_row1_col1`} span={24}>
              <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@wqtafp@upLoad_row1_col1_weaUpload`}
                  uploadUrl='/api/doc/upload/uploadFile2Doc'
                  uploadId='filename'
                  category='string'
                  limitType='jpg,png,pdf,jpeg'
                  useDefaultListB
                  //datas={upStatus === 'uploaded'  ? list : []}
                  datas={list}
                  autoUpload={true}
                  multiSelection={true}
                  sortable={false}
                  showOrder={true}
                  maxFilesNumber={10}
                  replaceWhenOver={false}
                  listType="list"
                  showClearAll={false}
                  onChange={(ids, uploadList) => {
                    // let listTemp = that.state.list;
                    // listTemp = listTemp.concat(uploadList);
                    // let idsTemp = mobx.toJS(excelFileNo).concat(ids);
                    that.setList(uploadList);
                    setExcelFileNo(ids);
                  }}
                  //clearWhenReset={false}
                  onUploading={status => this.onUploading(status)}
                  ref='upload'
                  //viewAttr={1}
              >
                <div style={{marginTop:-5}}><Button ecId={`${this && this.props && this.props.ecId || ''}_Button@esljms@upLoad_row1_col1_button`}>{getLabel(125333,'选择文件')}</Button></div>
              </WeaUpload>
            </Col>
          </Row>
      );
      
      return file;
    }
  
    onUploading = (status) => {
        const { list } = this.state;
        const { setLoding } = this.recognitionStore;;  

        this.setUpStatus(status);
        if (status == 'uploading') {
            setLoding(true);
            //this.setList([]);
        } else {
            setLoding(false);
            this.setList(list);
        }
    }

  setList = (list) => {
      this.setState({
          list: list
      });
  }

  setUpStatus = (upStatus) => {
      this.setState({
          upStatus: upStatus
      });
  }

  clear = () => {
    this.recognitionStore.setExcelFileNo([]);
    this.setState({
        list: [],
        upStatus: ''
    });    
  }
   /**************轮训识别************** */
   trainRecognition = (excelFileNo) => {
        const {setLoding,doTrainRecognition} = this.recognitionStore;
        setLoding(true);

        this.clear();

        let excelFileNoTemp = cloneDeep(mobx.toJS(excelFileNo));
        let fileid = excelFileNoTemp.shift();
        let formData = {
            fptpId:fileid,
            op:'recognition'
        };
        
        doTrainRecognition(formData,excelFileNoTemp,this.props.refreshInvoiceList);
   }

}

export default RecognitionModal;